package com.heima.publishwmnews.task;

import com.heima.feign.wemedia.Wemedia;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.pojo.WmNews;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Component
public class PublishWmNewsTaskRedis {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private  Wemedia wemedia;
    /**
     * 延迟文章发布
     */
    @Scheduled(cron = "0 * * * * ?")
    public  void  publish(){
        Set<String> ids = redisTemplate.opsForZSet().rangeByScore("wmnews", 0, System.currentTimeMillis());
        if (ids!=null &&!ids.isEmpty()){
            for (String id : ids) {
                ResponseResult<WmNews> responseResult= wemedia.getId(Integer.valueOf(id));
                 if (responseResult.getCode()== AppHttpCodeEnum.SUCCESS.getCode()){
                     WmNews wmNews = responseResult.getData();
                     if (wmNews.getStatus()==WmNews.Status.SUCCESS && wmNews.getPublishTime().before(new Date())){
                         wemedia.publish(wmNews);
                     }
                     redisTemplate.opsForZSet().remove("wmnews",id);
                 }
            }
        }

    }
}
